import businessApi from '@/api/modules/business'
import { getAuthorization, setAuthorization, removeToken } from '@/utils/auth'
import { publicKey, setSession, getSession } from '@/utils'
import { JSEncrypt } from 'jsencrypt'
import { resetRouter } from '@/router'

const user = {
  state: {
    projectId: getSession('projectId'),
    isSuperAdmin: getSession('isSuperAdmin'),
    token: getAuthorization(),
    userId: getSession('userId'),
    userName: getSession('userName'),
    avatar: '',
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      setAuthorization(token)
      state.token = token
    },
    SET_ID: (state, id) => {
      state.userId = id
      setSession('userId', id)
    },
    SET_NAME: (state, name) => {
      setSession('userName', name)
      state.userName = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PROJECTID: (state, projectId) => {
      state.projectId = projectId
    },
    SUPER_ADMIN: (state, isSuperAdmin) => {
      state.isSuperAdmin = isSuperAdmin
    }
  },

  actions: {
    // 验证用户名和密码
    verifyUser({commit}, userInfo) {
      const { loginName, loginPwd } = userInfo
      const key = publicKey()
      const encryptor = new JSEncrypt()
      encryptor.setPublicKey(key)
      const encrypted = encryptor.encrypt(loginPwd)
      return new Promise((resolve, reject) => {
        businessApi.checkUser({
          loginName: loginName,
          loginPwd: encrypted,
        }).then(response => {
          const data = response.data
          setSession('token', data.token)
          commit('SET_TOKEN', data.token)
          // commit('SET_NAME', data.userName)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 账号密码登录
    login({ commit }, checkInfo) {
      const { loginName, loginPwd, ip } = checkInfo
      const key = publicKey()
      const encryptor = new JSEncrypt()
      encryptor.setPublicKey(key)
      const encrypted = encryptor.encrypt(loginPwd)
      return new Promise((resolve, reject) => {
        businessApi.submitLogin({
          loginPwd: encrypted,
          loginName,
          ip
        }).then(response => {
          const data = response.data
          setSession('token', data.token)
          setSession('userId', data.userId)
          setSession('userName', data.userName)
          setSession('roleName', data.roleName)
          setSession('roleId', data.roleId)
          setSession('projectId', data.projectId)
          setSession('isSuperAdmin', String(data.isSuperAdmin))
          setSession('userProjectIdList', data.projectIdList)

          commit('SET_TOKEN', data.token)
          commit('SET_NAME', data.userName)
          commit('SET_ID', data.userId)
          commit('SET_ROLES', data.roleName)
          commit('SET_PROJECTID', data.projectId)
          commit('SUPER_ADMIN', String(data.isSuperAdmin))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 短信登录
    smsLogin({ commit }, checkInfo) {
      return new Promise((resolve, reject) => {
        businessApi.smsLogin(checkInfo).then(response => {
          const data = response.data
          setSession('token', data.token)
          setSession('userId', data.userId)
          setSession('userName', data.userName)
          setSession('roleName', data.roleName)
          setSession('roleId', data.roleId)
          setSession('projectId', data.projectId)
          setSession('isSuperAdmin', String(data.isSuperAdmin))
          setSession('userProjectIdList', data.projectIdList)

          commit('SET_TOKEN', data.token)
          commit('SET_NAME', data.userName)
          commit('SET_ID', data.userId)
          commit('SET_ROLES', data.roleName)
          commit('SET_PROJECTID', data.projectId)
          commit('SUPER_ADMIN', String(data.isSuperAdmin))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout({ dispatch, commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_NAME', '')
        commit('SET_ID', '')
        commit('SET_PROJECTID', '')
        localStorage.removeItem('token')
        localStorage.removeItem('userId')
        localStorage.removeItem('userName')
        localStorage.removeItem('roleName')
        localStorage.removeItem('roleId')
        localStorage.removeItem('projectId')
        localStorage.removeItem('isSuperAdmin')
        localStorage.removeItem('permission')
        localStorage.removeItem('menuPermission')
        removeToken()
        dispatch('tagsView/delAllViews')
        dispatch('clearRoutes').then(() => {
          resetRouter()
          resolve()
        })
      })
    },
    changeProject({ commit }, project) {
      return new Promise((resolve) => {
        setSession('projectId', project)
        commit('SET_PROJECTID', project)
        resolve()
      })
    },
  }
}

export default user
